package com.qxzn.app.desktoprobot;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.lmc.health.HealthFragment;
import com.lmc.recreation.RecreationFragment;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.bean.MainTabBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.adapter.FragmentAdapter;
import com.qxzn.app.page.interfaces.MyInterface;
import com.qxzn.app.page.model.MineModel;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.personalcenter.activity.LoginByPwdActivity;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.DrawableUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.module.home.fragment.HomeFragment;
import com.qxzn.module.mine.fragment.MineFragment;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MainActivity extends BaseActivity implements MyInterface.AgreeInvitationListener {
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;

    private String tabJson = "{\"text_color_select\":\"#2A8CFF\",\"text_color_unselect\":\"#2A2A2A\",\"tab_bg\":\"#ffffff\",\"can_scale\":\"true\",\"tab\":[{\"tab_name\":\"首页\",\"tab_img_select\":\"tab_one_select\",\"tab_img_placeholder_select\":\"logo\",\"tab_img_error_select\":\"logo\",\"tab_img_placeholder_unselect\":\"logo\",\"tab_img_error_unselect\":\"logo\",\"tab_img_unselect\":\"tab_one_unselect\"},{\"tab_name\":\"健康\",\"tab_img_select\":\"tab_two_select\",\"tab_img_placeholder_select\":\"logo\",\"tab_img_error_select\":\"logo\",\"tab_img_placeholder_unselect\":\"logo\",\"tab_img_error_unselect\":\"logo\",\"tab_img_unselect\":\"tab_two_unselect\"},{\"tab_name\":\"娱乐\",\"tab_img_select\":\"tab_three_select\",\"tab_img_placeholder_select\":\"logo\",\"tab_img_error_select\":\"logo\",\"tab_img_placeholder_unselect\":\"logo\",\"tab_img_error_unselect\":\"logo\",\"tab_img_unselect\":\"tab_three_unselect\"},{\"tab_name\":\"我的\",\"tab_img_select\":\"tab_four_select\",\"tab_img_placeholder_select\":\"logo\",\"tab_img_error_select\":\"logo\",\"tab_img_placeholder_unselect\":\"logo\",\"tab_img_error_unselect\":\"logo\",\"tab_img_unselect\":\"tab_four_unselect\"}]}";
    //    private String tabJson = "{\"text_color_select\":\"#2A8CFF\",\"text_color_unselect\":\"#2A2A2A\",\"tab_bg\":\"#ffffff\",\"can_scale\":\"true\",\"tab\":[{\"tab_name\":\"首页\",\"tab_img_select\":\"tab_one_select\",\"tab_img_placeholder_select\":\"logo\",\"tab_img_error_select\":\"logo\",\"tab_img_placeholder_unselect\":\"logo\",\"tab_img_error_unselect\":\"logo\",\"tab_img_unselect\":\"tab_one_unselect\"},{\"tab_name\":\"我的\",\"tab_img_select\":\"tab_four_select\",\"tab_img_placeholder_select\":\"logo\",\"tab_img_error_select\":\"logo\",\"tab_img_placeholder_unselect\":\"logo\",\"tab_img_error_unselect\":\"logo\",\"tab_img_unselect\":\"tab_four_unselect\"}]}";
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private MainTabBean bean;
    private FragmentAdapter fragmentAdapter;
    private CommonNavigator commonNavigator;
    private long exitTime;
    private MineModel mineModel;

    @Override
    protected int initLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void iniTitleBar() {
        rl_title.setVisibility(View.GONE);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        bean = JSON.parseObject(tabJson, MainTabBean.class);
        initFragments(bean);
        fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), mFragments);
        viewPager.setAdapter(fragmentAdapter);
//        viewPager.setPageTransformer(true, new DepthPageTransformer());//设置ViewPager切换动画
        viewPager.setOffscreenPageLimit(bean.getTab().size() - 1);
//        ViewPagerScroller scroller = new ViewPagerScroller(this);
//        scroller.setScrollDuration(600);//设置ViewPager切换过渡时间（单位：ms）
//        scroller.initViewPagerScroll(viewPager);
        initMagicIndicator1();
//        SharePreferenceUtil.setUserName(this, "17612709290");
//        SharePreferenceUtil.setPwd(this, "a12345678");
//        SharePreferenceUtil.setUserName(this, "15134552845");
//        SharePreferenceUtil.setPwd(this, "qxzn6688");
//        getKey();
        mineModel = new MineModel(this);
        mineModel.setAgreeInvitationListener(this);
    }

    @Override
    public void onEventBus(EventBusBean busBean) {
        super.onEventBus(busBean);
        if (busBean.getId() == Constant.EventBusId.ERROR_KEY) {
            AppUtil.showLog("onEventBus：" + (Thread.currentThread() == Looper.getMainLooper().getThread()));
//            getKey();
            startActivity(LoginByPwdActivity.class);
        } else if (busBean.getId() == Constant.EventBusId.INVITATION_TO_MEMBER) {
            JSONObject jsonObject = (JSONObject) busBean.getObject();
            showInvitationDialog(jsonObject);
        }
    }

    private void showInvitationDialog(JSONObject jsonObject) {
        showDialog("家庭圈邀请", "小π机器人ID为" + jsonObject.getString("device_id") + "的用户“" + jsonObject.getString("niname") +
                "”邀请你加入该家庭圈", "拒绝", "同意", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                agreeInvitation(jsonObject, -4);
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                agreeInvitation(jsonObject, 1);
            }
        });
    }

    private void agreeInvitation(JSONObject jsonObject, int roles) {
        showProgress();
        JSONObject params = new JSONObject();
        params.put("device_id", jsonObject.getString("device_id"));
        params.put("username", SharePreferenceUtil.getUserName(this));
        params.put("roles", roles);
        mineModel.agreeInvitation(params, roles);
    }

    private List<Fragment> initFragments(MainTabBean bean) {
        mFragments.clear();
        HomeFragment homeFragment = new HomeFragment();
        Bundle bundle1 = new Bundle();
        bundle1.putString("title", bean.getTab().get(0).getTab_name());
        homeFragment.setArguments(bundle1);
        mFragments.add(homeFragment);

        HealthFragment healthFragment = new HealthFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putString("title", bean.getTab().get(1).getTab_name());
        healthFragment.setArguments(bundle2);
        mFragments.add(healthFragment);

        RecreationFragment contactsFragment = new RecreationFragment();
        Bundle bundle3 = new Bundle();
        bundle3.putString("title", bean.getTab().get(2).getTab_name());
        contactsFragment.setArguments(bundle3);
        mFragments.add(contactsFragment);

        MineFragment contactsFragment4 = new MineFragment();
        Bundle bundle4 = new Bundle();
        bundle4.putString("title", bean.getTab().get(1).getTab_name());
        contactsFragment4.setArguments(bundle4);
        mFragments.add(contactsFragment4);

        return mFragments;
    }

    private void initMagicIndicator1() {
        magicIndicator.setBackgroundColor(Color.parseColor(bean.getTab_bg()));
        commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return bean.getTab().size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);

                // load custom layout
                View customLayout = LayoutInflater.from(context).inflate(R.layout.item_tab_main, null);
                final ImageView iv_tab = (ImageView) customLayout.findViewById(R.id.iv_tab);
                final TextView tv_tab = (TextView) customLayout.findViewById(R.id.tv_tab);
//                iv_tab.setImageResource(R.mipmap.ic_launcher);
                Glide.with(MainActivity.this).load(DrawableUtil.getImgResource(MainActivity.this, bean.getTab().get(index).getTab_img_unselect()))
                        .apply(new RequestOptions().placeholder(DrawableUtil.getImgResource(MainActivity.this, bean.getTab().get(index).getTab_img_placeholder_unselect()))
                                .error(DrawableUtil.getImgResource(MainActivity.this, bean.getTab().get(index).getTab_img_error_unselect()))).into(iv_tab);
                tv_tab.setText(bean.getTab().get(index).getTab_name());
                commonPagerTitleView.setContentView(customLayout);

                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {

                    @Override
                    public void onSelected(int index, int totalCount) {
                        tv_tab.setTextColor(Color.parseColor(bean.getText_color_select()));
                        Glide.with(MainActivity.this).load(DrawableUtil.getImgResource(MainActivity.this, bean.getTab().get(index).getTab_img_select()))
                                .apply(new RequestOptions().placeholder(DrawableUtil.getImgResource(MainActivity.this, bean.getTab().get(index).getTab_img_placeholder_select()))
                                        .error(DrawableUtil.getImgResource(MainActivity.this, bean.getTab().get(index).getTab_img_error_select()))).into(iv_tab);
                    }

                    @Override
                    public void onDeselected(int index, int totalCount) {
                        tv_tab.setTextColor(Color.parseColor(bean.getText_color_unselect()));
                        Glide.with(MainActivity.this).load(DrawableUtil.getImgResource(MainActivity.this, bean.getTab().get(index).getTab_img_unselect()))
                                .apply(new RequestOptions().placeholder(DrawableUtil.getImgResource(MainActivity.this, bean.getTab().get(index).getTab_img_placeholder_unselect()))
                                        .error(DrawableUtil.getImgResource(MainActivity.this, bean.getTab().get(index).getTab_img_error_unselect()))).into(iv_tab);
                    }

                    @Override
                    public void onLeave(int index, int totalCount, float leavePercent, boolean leftToRight) {
//                        iv_tab.setScaleX(1.3f + (0.8f - 1.3f) * leavePercent);
//                        iv_tab.setScaleY(1.3f + (0.8f - 1.3f) * leavePercent);
                    }

                    @Override
                    public void onEnter(int index, int totalCount, float enterPercent, boolean leftToRight) {
//                        iv_tab.setScaleX(0.8f + (1.3f - 0.8f) * enterPercent);
//                        iv_tab.setScaleY(0.8f + (1.3f - 0.8f) * enterPercent);
                    }
                });

                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewPager.setCurrentItem(index,false);
                    }
                });

                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, viewPager);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                exitTime = System.currentTimeMillis();
                AppUtil.showShortToast(this, "再按一次退出");
            } else {//两次点击小于2秒
                finish();
            }
//            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onAgreeInvitationSuccess(BaseBean baseBean, int roles) {
        hideProgress();
        if (baseBean != null) {
            if (baseBean.getCode() == 200) {
                if (roles == 1) {
                    ToastUtil.showImgToast(this, "已同意", com.qxzn.module.mine.R.mipmap.icon_success);
                } else {
                    ToastUtil.showImgToast(this, "已拒绝", com.qxzn.module.mine.R.mipmap.icon_success);
                }
                return;
            }
        }
        if (baseBean != null && !TextUtils.isEmpty(baseBean.getMsg())) {
            ToastUtil.showImgToast(this, baseBean.getMsg(), com.qxzn.module.mine.R.mipmap.icon_failed);
        } else {
            ToastUtil.showImgToast(this, "操作失败，请重试", com.qxzn.module.mine.R.mipmap.icon_failed);
        }
    }

    @Override
    public void onAgreeInvitationFailure() {
        hideProgress();
        ToastUtil.showTextToast(this, getString(R.string.network_error));
    }
}
